package com.server.server_a10.management.controller;

import com.server.server_a10.entity.Inform;
import com.server.server_a10.management.entity.ManageInf;
import com.server.server_a10.management.entity.RoomInf;
import com.server.server_a10.mapper.RoomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class manageRoomHandle {
    @Autowired
    RoomMapper roomMapper;


//    当name（此处的name为房间id）和home_id均为null的时候为获取全部的房间
//    当name为null而home_id不为null的时候获取房子内全部的房间
    @Transactional
    @GetMapping(value = "/adminGetAllRoom")
    public ManageInf adminShowUser(@RequestParam("limit") int limit,
                                   @RequestParam("page") int page,
                                   @RequestParam("name") String name,
                                   @RequestParam("home_id") String home_id) {

        ManageInf inform = new ManageInf();

        int index = (page - 1) * limit;

        List<RoomInf> rooms;

        rooms = roomMapper.getRoomLimit(name, index, limit,home_id);

        int count = roomMapper.getRoomLimitCount(name);

        inform.setCount(count);
        if (rooms.isEmpty()) {
            inform.isNull("似乎没有任何数据");
        } else {
            inform.success("信息加载成功", rooms);
        }
        return inform;
    }

//    删除房间
    @PostMapping(value = "/delRoomById")
    public Inform delRoomById(@RequestBody Map<String,Integer> request){
        Inform inform = new Inform();

        int id = request.get("id");
        int res = 0;
        try {
            res = roomMapper.delRoomById(id);
        }catch (Exception e){
            inform.isNull("删除失败，请检查信息");
            return inform;
        }

        if (res == 1){
            inform.success("删除成功",null);
        }else {
            inform.isNull("删除失败，请检查信息");
        }

        return inform;
    }

//    添加房间
    @PostMapping(value = "/addRoom")
    public Inform addRoom(@RequestBody Map<String,Object> request){
        Inform inform = new Inform();

        String name  =  (String) request.get("name");
        int home_id  =  (int) request.get("home_id");

        int insRoom = 0;
        try {
            insRoom = roomMapper.insRoom(name,home_id);
        }catch (Exception e){
            inform.fail("信息格式错误,没有该房子",null);
            return inform;
        }

        if (insRoom == 0){
            inform.isNull("插入失败");
        }else {
            inform.success("房间创建成功",null);
        }

        return inform;
    }

}
